package com.xhp.xtool.util.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class FtpClientPool {

	private final GenericObjectPool<FTPClient> internalPool;

	public FtpClientPool(FtpClientFactory factory) {
		FtpConfig ftp = factory.getFtpConfig();
		GenericObjectPoolConfig<FTPClient> poolConfig = new GenericObjectPoolConfig<>();
		poolConfig.setMaxTotal(ftp.getMaxTotal());
		poolConfig.setMinIdle(ftp.getMinIdle());
		poolConfig.setMaxIdle(ftp.getMaxIdle());
		this.internalPool = new GenericObjectPool<>(factory, poolConfig);
	}

	// 从连接池中取连接
	public FTPClient getFtpClient() throws Exception {
		try {
			return internalPool.borrowObject();
		} catch (Exception e) {
			throw new Exception(e);
//			e.printStackTrace();
//			return null;
		}
	}

	// 将连接归还到连接池
	public void returnFTPClient(FTPClient ftpClient) {
		try {
			internalPool.returnObject(ftpClient);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
